﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Web.Core;
using System.Collections;
using System.Collections.Specialized;

namespace Yuanlin.Business
{
    public class CompanyFisheryAddControl : YuanlinUserControl
    {
        protected ValuedTextBox titleValuedTextBox;//名称
        protected ValuedTextBox pinNameTitleValuedTextBox;//品种
        protected RadioButtonList categoryRadioButtonList;//植物分类
        protected CheckBoxList applicationCategoryCheckBoxList;
        protected ValuedTextBox numberValuedTextBox;//数量
        protected ValuedTextBox priceValuedTextBox;//价格
        protected CheckBoxList aquacultureMethodCheckBoxList;//养殖方式
        protected CheckBoxList aquacultureAttributeCheckBoxList;//养殖属性
        protected ValuedTextBox registerTrademarkValuedTextBox;//注册商标
        protected ValuedCheckBox productPriceFromFaceCheckBox;//是否面议
        protected RadioButtonList expiredInfoRadioButtonList;//信息有效期
        protected ValuedEditor descriptionValuedEditor;
        protected ValuedTextBox miJingValuedTextBox;//米经
        protected ValuedTextBox diJingValuedTextBox;//地径
        protected HiddenField specificationHiddenField;
        protected HiddenField applicationSpecificationHiddenField;
        protected HiddenField hdnAppCategory;
        protected Literal addProductLiteral;
        protected HtmlInputFile attachmentData;
        protected IButton SaveButton;
        protected IButton BackButton;
        private YuanlinUser user = HttpContext.Current.User as YuanlinUser;
        private string tradeType = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.TradeType);

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack && !AjaxManager.IsCallBack)
            {
                Bind();
            }
            SaveButton.Click += new EventHandler(SaveButton_Click);
            BackButton.Click += new EventHandler(BackButton_Click);
            AjaxManager.Register(this, "AjaxMethod");
        }

        public void BackButton_Click(object sender, EventArgs e)
        {
            PageRedirect();
        }

        public void SaveButton_Click(object sender, EventArgs e)
        {
            CompanyFishery product = new CompanyFishery();

            product.Title.Value = CensorWordManager.CensorWord(titleValuedTextBox.Value);
            product.PinNameTitle.Value = CensorWordManager.CensorWord(pinNameTitleValuedTextBox.Value);
            product.TradeType.Value = tradeType;//Url传过来
            product.CategoryId.Value = Int32.Parse(categoryRadioButtonList.SelectedValue);
            product.Number.Value = this.numberValuedTextBox.Value.Length == 0 ? 0 : Convert.ToInt32(this.numberValuedTextBox.Value);
            product.Price.Value = priceValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(priceValuedTextBox.Text));
            product.MiJing.Value = miJingValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(miJingValuedTextBox.Text));
            product.DiJing.Value = diJingValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(diJingValuedTextBox.Text));
            foreach (ListItem item in this.aquacultureMethodCheckBoxList.Items)
            {
                if (item.Selected)
                {
                    product.AquacultureMethod.Value += "," + item.Value;
                }
            }
            if (product.AquacultureMethod.Value.Length > 0)
            {
                product.AquacultureMethod.Value = product.AquacultureMethod.Value.Substring(1);
            }
            foreach (ListItem item in this.aquacultureAttributeCheckBoxList.Items)
            {
                if (item.Selected)
                {
                    product.AquacultureAttribute.Value += "," + item.Value;
                }
            }
            if (product.AquacultureAttribute.Value.Length > 0)
            {
                product.AquacultureAttribute.Value = product.AquacultureAttribute.Value.Substring(1);
            }
            product.RegisterTrademark.Value = CensorWordManager.CensorWord(registerTrademarkValuedTextBox.Value);
            product.ProductPriceFromFace.Value = this.productPriceFromFaceCheckBox.Value.ToLower() == "false" ? 0 : 1;
            product.ExpiredInfo.Value = Int32.Parse(expiredInfoRadioButtonList.SelectedValue);
            product.Body.Value = CensorWordManager.CensorWord(this.descriptionValuedEditor.Value);

            product.Province.Value = user.Province.Value;
            product.City.Value = user.City.Value;
            product.Town.Value = user.Town.Value;
            product.SmallTown.Value = user.SmallTown.Value;
            product.CompanyName.Value = user.CompanyName.Value;
            product.UserId.Value = user.EntityId.Value;
            product.GreenNum.Value = user.CurrentGreenNumber;
            product.CreateDate.Value = DateTime.Now;
            product.UpdateDate.Value = DateTime.Now;

            List<string> fieldNames = new List<string>();
            List<string> fieldValues = new List<string>();
            List<string> fieldUnits = new List<string>();
            if (specificationHiddenField.Value.Length > 0)
            {
                string[] specifications = specificationHiddenField.Value.Split(';');
                foreach (string item in specifications)
                {
                    fieldNames.Add(item.Split(':')[0]);
                    fieldValues.Add(item.Split(':')[1]);
                    fieldUnits.Add(item.Split(':')[2]);
                }
            }
            product.GuiGeNames.Value = string.Join("|", fieldNames.ToArray());
            product.GuiGeValues.Value = string.Join("|", fieldValues.ToArray());
            product.GuiGeUnits.Value = string.Join("|", fieldUnits.ToArray());

            SetProductId(product);

            BusinessManager.CreateCompanyFishery(product);

            //创建与应用分类的关系
            CompanyFisheryAndAppCategoryRelation relation = new CompanyFisheryAndAppCategoryRelation();
            relation.FisheryId.Value = product.EntityId.Value;
            foreach (ListItem item in this.applicationCategoryCheckBoxList.Items)
            {
                if (item.Selected)
                {
                    relation.CategoryIds += "," + Globals.ChangeType<int>(item.Value);
                }
            }
            if (!string.IsNullOrEmpty(relation.CategoryIds))
            {
                relation.CategoryIds = relation.CategoryIds.Substring(1);
                BusinessManager.CreateCompanyFisheryAndAppCategoryRelation(relation);
            }

            //创建反馈信息
            AquacultureListRequest request = new AquacultureListRequest();
            request.EqualTitle = product.Title.Value;
            request.CategoryType = (int)CategoryType.Fishery;
            EntityList products = BusinessManager.GetAquacultureList(RequestHelper.BuildGetAquacultureListRequest(request));
            if (products.Count == 0)
            {
                AquacultureFeedback feedback = new AquacultureFeedback();
                feedback.Title.Value = product.Title.Value;
                feedback.GreenNum.Value = user.RegisterGreenNumber.Value; ;
                feedback.UserId.Value = user.EntityId.Value;
                feedback.CreateDate.Value = DateTime.Now;
                feedback.CompanyAquacultureId.Value = product.EntityId.Value;
                feedback.CompanyContactPhone.Value = user.CompanyContactPhone.Value;
                feedback.CompanyEmail.Value = user.CompanyEmail.Value;
                feedback.CompanyQQ.Value = user.CompanyQQ.Value;
                feedback.CategoryType.Value = (int)CategoryType.Fishery;
                BusinessManager.CreateAquacultureFeedback(feedback);
            }

            if (SiteUrls.Instance().IsAttachmentValid(attachmentData))
            {
                product.AttachmentFileName.Value = SiteUrls.Instance().GetPostedFileName(attachmentData);
                BusinessManager.UpdateCompanyFishery(product);
                SiteUrls.Instance().SaveFile(SiteUrls.Instance().GetFile(product), attachmentData);
            }

            switch (tradeType)
            {
                case "0":
                    {
                        user.Fishery = GetFisheryNum(user.Fishery);
                    }
                    break;
                case "2":
                    {
                        user.FisheryQiuGou = GetFisheryNum(user.FisheryQiuGou);
                    }
                    break;
                case "1":
                    {
                        user.FisheryJingPin = GetFisheryNum(user.FisheryJingPin);
                    }
                    break;
                case "3":
                    {
                        user.FisheryJiShou = GetFisheryNum(user.FisheryJiShou);
                    }
                    break;
            }
            UserManager.UpdateUser(user);
            string alertStr = "alert('添加成功！{0}');";
            alertStr = string.Format(alertStr, product.Verify.Value == 0 ? "此信息审核中。" : "");
            this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "CompanyFishery", alertStr, true);
            ClearControl();
        }
        private void PageRedirect()
        {
            if (tradeType == "0")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyFisheryListUrl());
            }
            else if (tradeType == "2")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyFisheryQiuGouListUrl());
            }
            else if (tradeType == "1")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyFisheryJingPinListUrl());
            }
            else if (tradeType == "3")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyFisheryJiShouListUrl());
            }
        }
        private void ClearControl()
        {
            numberValuedTextBox.Text = "";
            priceValuedTextBox.Text = "";
            categoryRadioButtonList.SelectedIndex = -1;
        }
        private string GetFisheryNum(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                str = "1";
            }
            else
            {
                str = (Globals.ChangeType<int>(str) + 1).ToString();
            }
            return str;
        }
        private void Bind()
        {
            //种类
            AquacultureCategoryListRequest request = new AquacultureCategoryListRequest();
            request.CategoryType = (int)CategoryType.Fishery;
            EntityList categories = BusinessManager.GetAquacultureCategoryList(RequestHelper.BuildGetAquacultureCategoryListRequest(request));
            this.categoryRadioButtonList.DataSource = categories;
            this.categoryRadioButtonList.DataTextField = "Title";
            this.categoryRadioButtonList.DataValueField = "EntityId";
            this.categoryRadioButtonList.DataBind();

            //应用分类
            AquacultureAppCategoryListRequest request1 = new AquacultureAppCategoryListRequest();
            request1.CategoryType = (int)CategoryType.Fishery;
            EntityList applicationCategories = BusinessManager.GetAquacultureAppCategoryList(RequestHelper.BuildGetAquacultureAppCategoryListRequest(request1));
            applicationCategoryCheckBoxList.DataSource = applicationCategories;
            applicationCategoryCheckBoxList.DataValueField = "EntityId";
            applicationCategoryCheckBoxList.DataTextField = "Title";
            applicationCategoryCheckBoxList.DataBind();
            hdnAppCategory.Value = "";
            if (applicationCategories.Count > 0)
            {
                string listValue = "";
                foreach (AquacultureAppCategory item in applicationCategories)
                {
                    listValue += "," + item.EntityId.Value.ToString();
                }
                hdnAppCategory.Value = listValue.Substring(1);
            }
            //种植方式
            EntityList aquacultureMethods = BusinessManager.GetAquacultureMethodList(RequestHelper.BuildGetAquacultureMethodListRequest());
            aquacultureMethodCheckBoxList.DataSource = aquacultureMethods;
            aquacultureMethodCheckBoxList.DataValueField = "EntityId";
            aquacultureMethodCheckBoxList.DataTextField = "Title";
            aquacultureMethodCheckBoxList.DataBind();

            //苗木属性
            EntityList aquacultureAttributes = BusinessManager.GetAquacultureAttributeList(RequestHelper.BuildGetAquacultureAttributeListRequest());
            aquacultureAttributeCheckBoxList.DataSource = aquacultureAttributes;
            aquacultureAttributeCheckBoxList.DataValueField = "EntityId";
            aquacultureAttributeCheckBoxList.DataTextField = "Title";
            aquacultureAttributeCheckBoxList.DataBind();

            //信息有效期
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("5天", "1"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("15天", "2"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("一个月", "3"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("三个月", "4"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("六个月", "5"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("九个月", "6"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("十二个月", "7"));
            expiredInfoRadioButtonList.SelectedIndex = 0;

            switch (tradeType)
            {
                case "0":
                    {
                        addProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_AddCompanyFishery", "ControlPanelResources.xml");
                    }
                    break;
                case "2":
                    {
                        addProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_AddCompanyFisheryQiuGou", "ControlPanelResources.xml");
                    }
                    break;
                case "1":
                    {
                        addProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_AddCompanyFisheryJingPin", "ControlPanelResources.xml");
                    }
                    break;
                case "3":
                    {
                        addProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_AddCompanyFisheryJiShou", "ControlPanelResources.xml");
                    }
                    break;
            }
        }
        private void SetProductId(CompanyFishery companyFishery)
        {
            AquacultureListRequest request = new AquacultureListRequest();
            request.EqualTitle = companyFishery.Title.Value;
            request.CategoryType = (int)CategoryType.Fishery;
            EntityList products = BusinessManager.GetAquacultureList(RequestHelper.BuildGetAquacultureListRequest(request));
            if (products.TotalCount > 0)
            {
                companyFishery.FisheryId.Value = products[0].EntityId.Value;
                companyFishery.Verify.Value = 1;
            }
            else
            {
                companyFishery.Verify.Value = 0;
            }
        }

        #region Ajax Method

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string ParentCategorySelectedChanged(string selectedValue)
        {
            if (string.IsNullOrEmpty(selectedValue))
            {
                return "";
            }

            return BindProductsAndSpecifications(int.Parse(selectedValue));
        }
        private string BindProductsAndSpecifications(int categoryID)
        {
            string returnValue = string.Empty;
            if (categoryID < 0)
            {
                return returnValue;
            }

            //绑定规格
            AquacultureGuiGeListRequest request = new AquacultureGuiGeListRequest();
            request.CategoryId = categoryID;
            EntityList guiges = BusinessManager.GetAquacultureGuiGeList(RequestHelper.BuildGetAquacultureGuiGeListRequest(request));
            if (guiges.Count > 0)
            {
                string format = "{0}:{1}";
                string str = string.Empty;
                foreach (AquacultureGuiGe guige in guiges)
                {
                    if (str != string.Empty)
                    {
                        str += ";";
                    }
                    str += string.Format(format, guige.Title, guige.Unit);
                }
                returnValue = str;
            }

            return returnValue;
        }

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string GetQueryStr(string userInputStr)
        {
            string returnStr = string.Empty;
            AquacultureListRequest request = new AquacultureListRequest();
            request.CategoryId = 0;
            request.QueryValue = userInputStr;
            request.CategoryType = (int)CategoryType.Fishery;
            request.PageIndex = 0;
            request.PageSize = 1500;
            EntityList aquacultures = BusinessManager.GetAquacultureList(RequestHelper.BuildGetAquacultureListRequest(request));
            if (aquacultures.Count == 0)
            {
                return returnStr;
            }
            string title = string.Empty;
            string category = string.Empty;
            string appCategory = string.Empty;
            string avgPrice = string.Empty;
            string formatStr = ",{0}";
            CompanyFisheryAndAppCategoryRelationListRequest categoryRequest = null;
            EntityList categoryRelations = null;
            foreach (Aquaculture item in aquacultures)
            {
                if (item.Alias.Value.Length > 0)
                {
                    title += string.Format(formatStr + "({1})", item.Title.Value, item.Alias.Value);
                }
                else
                {
                    title += string.Format(formatStr, item.Title.Value);
                }
                category += string.Format(formatStr,item.CategoryId.Value);
                avgPrice += string.Format(formatStr, item.AvgPrice.Value);

                categoryRequest = new CompanyFisheryAndAppCategoryRelationListRequest();
                categoryRequest.FisheryId = item.EntityId.Value;
                categoryRelations = BusinessManager.GetCompanyFisheryAndAppCategoryRelationList(RequestHelper.BuildGetCompanyFisheryAndAppCategoryRelationListRequest(categoryRequest));
                if (categoryRelations.Count > 0)
                {
                    foreach (CompanyFisheryAndAppCategoryRelation categoryItem in categoryRelations)
                    {
                        appCategory += string.Format(formatStr, categoryItem.CategoryId.Value);
                    }
                }
            }

            returnStr = string.Format("{0}|{1}|{2}|{3}", title.Trim(','), category.Trim(','), appCategory.Trim(','), avgPrice.Trim(','));

            return returnStr;
        }

        #endregion
    }
}